package com.cbc.ourgame.slideshowmaker.components.audio
{
	import assets.audiochooser.AudioToggle;
	import assets.volume.SmallVolumeControlAsset;
	
	import com.cbc.ourgame.slideshowmaker.components.ui.FlyUpMenu;
	import com.cbc.ourgame.slideshowmaker.components.ui.FrameButton;
	import com.cbc.ourgame.slideshowmaker.events.AudioSelectionEvent;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	
	[Event (name="audioSelection", type="com.cbc.ourgame.slideshowmaker.events.AudioSelectionEvent")]
	
	public class AudioPanel extends EventDispatcher
	{
		private var _parent:DisplayObjectContainer;
		private var _selector:FlyUpMenu;
		private var _volumeControl:VolumeController;
		private var _playToggle:FrameButton;
		private var _isPlaying:Boolean;
	
		private var _callback:Function;
		
		private var _currentTrack:URLRequest;
		private var _trackID:String;
		
		public function get volume():Number { return _volumeControl.volume; }
		public function set volume(value:Number):void { _volumeControl.volume = value; }
		
		public function get currentTrack():URLRequest { return _currentTrack; }
		public function get trackID():String { return _trackID; }
		
		public function AudioPanel(selector:FlyUpMenu, playToggle:AudioToggle, control:SmallVolumeControlAsset)
		{	
			_parent = playToggle.parent;
			_selector = selector;
			_playToggle = new FrameButton(playToggle);
			_playToggle.addCallback(onPlayClick);
			_playToggle.view.icon.gotoAndStop(1);
			_volumeControl = new VolumeController(null, control);
			
			_selector.addClickCall(onAudioSelect);
			_isPlaying = false;
			_currentTrack = MenuItem(_selector.menuItems[_selector.currentSelection]).request;
			_trackID = MenuItem(_selector.menuItems[_selector.currentSelection]).id;
		}
		
		public function addPlayCallback(callback:Function):void
		{
			_callback = callback;	
		}
		
		public function show():void
		{
			_parent.addChild(_selector.view);
			_parent.addChild(_playToggle.view);
			_parent.addChild(_volumeControl.view);
		}
		
		public function hide():void
		{
			_parent.removeChild(_selector.view);
			_parent.removeChild(_playToggle.view);
			_parent.removeChild(_volumeControl.view);
			
			_isPlaying = true;
			onPlayClick(null);
		}
		
		private function onPlayClick(e:MouseEvent):void
		{
			_isPlaying = !_isPlaying;
			
			if(_isPlaying) _playToggle.view.icon.gotoAndStop(2);
			else _playToggle.view.icon.gotoAndStop(1);
			
			_callback(_isPlaying);
		}
		
		private function onAudioSelect(request:URLRequest, id:String):void
		{
			dispatchEvent(new AudioSelectionEvent(AudioSelectionEvent.AUDIO_SELECTION, request, id));
			_currentTrack = request;
			//_isPlaying = true;
			//onPlayClick(null);
		}

	}
}